package com.tony.ai.ai

import android.graphics.Bitmap
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.TextRecognizer
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions

/**
 * 图像识别工具类
 */
class TextRecognitionHelper {
    companion object {
        const val DESIRED_WIDTH_CROP_PERCENT = 8
        const val DESIRED_HEIGHT_CROP_PERCENT = 74
        val imageCropPercentages = MutableLiveData<Pair<Int, Int>>()
            .apply { value = Pair(DESIRED_HEIGHT_CROP_PERCENT, DESIRED_WIDTH_CROP_PERCENT) }
    }
    private val TAG = "TextRecognitionHelper"
    private var recognizer: TextRecognizer? = null

    init {
        recognizer = TextRecognition.getClient(ChineseTextRecognizerOptions.Builder().build())
    }


    /**
     * 开始执行
     */
    fun startProcess(bitmap: Bitmap,onTextResult:(result:String?)->Unit) {
        val image = InputImage.fromBitmap(bitmap, 0)
        recognizer?.process(image)?.addOnSuccessListener {
            Log.e(TAG, "${it.text}")
            Log.e(TAG, "-----------------------------------------")
            onTextResult(it.text)
        }?.addOnFailureListener {
            Log.e(TAG, "${it.message}")
        }
    }
}